use db_yule8x_agent
GO

if exists(select * from sysobjects where name='proc_withdraw_unaudit' and xtype='P')
drop procedure proc_withdraw_unaudit
GO

-- 撤销提现审核
-- 规则：
--		审核成功：账户余额不变，冻结金额减去提现金额
--		审核失败：账户余额增加提现金额，冻结金额减去提现金额
-- 返回 1表示成功;0表示失败
create procedure proc_withdraw_unaudit(
	@pint_id int,				-- 提现申请记录ID
	@pint_auditor_id int,		-- 审核员用户ID
	@pint_status INT,			-- 审核结果
	@pstr_remark VARCHAR(128),	-- 审核备注
	@pstr_output varchar(120) output
)
as
begin
	declare @vint_account_id int;
	DECLARE @vdec_blance DECIMAL(9,2);
	DECLARE @vdec_frozen_blance DECIMAL(9,2);
	declare @vdec_amount decimal(9,2); -- 提现金额
	declare @vint_uid int;
	
	-- 判断提现表，防止重复回调
	select @vint_uid=w.user_id, @vdec_amount=w.amount, @vint_account_id=a.account_id, @vdec_blance=a.blance, @vdec_frozen_blance=a.frozen_blance from dbo.t_finance_withdraw w INNER JOIN dbo.t_user_finance_account a ON w.user_id=a.user_id where w.id=@pint_id AND w.status > 0;
	if @vint_uid IS NULL
	begin
		set @pstr_output='{"code":"", "name":"ORDER HAS DONE", "text":"提现申请不存在或未审核, 无需操作"}';
		return 0;
	end
	// 。。。。。
	set @vdec_frozen_blance=@vdec_frozen_blance-@vdec_amount;
	if @vdec_frozen_blance < 0
	begin
		set @pstr_output='{"code":"", "name":"OUT OF FROZEN BLANCE", "text":"提现金额不能超过不可用余额"}';
		return 0;		
	end 
	
	IF @pint_status=1
	BEGIN
		-- 审核成功，冻结金额减少，余额不变
		UPDATE dbo.t_user_finance_account SET frozen_blance=@vdec_frozen_blance WHERE user_id=@vint_uid;
		-- 写入资金明细表，交易类型(1:充值,2:返现;3:提现;4:赠送;5:领取;6:转换;)
		SET @vdec_blance=@vdec_blance+@vdec_amount; 
		INSERT into t_finance_transaction_details ([account_id] ,[user_id] ,[trade_type] ,[amount] , [pay_channel] ,[blance] ,[remark] ,[status]) 
			VALUES (@vint_account_id, @vint_uid, 3, -@vdec_amount, 'bank', @vdec_blance, @pstr_remark, 1);
	END
	ELSE
	BEGIN
		-- 审核失败，冻结金额减少，余额增加
		UPDATE dbo.t_user_finance_account SET frozen_blance=@vdec_frozen_blance, blance=blance+@vdec_amount WHERE user_id=@vint_uid;		
	END
	
	-- 更新本条记录
	update t_finance_withdraw set status=@pint_status, rejected_remark=@pstr_remark, auditor_id=@pint_auditor_id, audit_time=GETDATE() where id=@pint_id;
		
	set @pstr_output='{"code":"", "name":"SUCCESS", "text":"操作成功"}';
	return 1;
end
GO
